#!/usr/bin/env python3
"""
Text2SQL评估系统简化后端启动脚本
不依赖Ragas，使用基础依赖
"""
import os
import sys
import subprocess

def check_requirements():
    """检查基础依赖是否安装"""
    try:
        import flask
        import numpy
        import sqlparse
        print("✓ 基础依赖已安装")
        return True
    except ImportError as e:
        print(f"✗ 缺少依赖: {e}")
        return False

def install_requirements():
    """安装基础依赖"""
    print("正在安装基础依赖...")
    try:
        subprocess.check_call([sys.executable, "-m", "pip", "install", "-r", "backend/requirements-basic.txt"])
        print("✓ 基础依赖安装完成")
        return True
    except subprocess.CalledProcessError as e:
        print(f"✗ 依赖安装失败: {e}")
        return False

def check_env_file():
    """检查环境变量文件"""
    env_file = "backend/.env"
    if not os.path.exists(env_file):
        print("⚠ 未找到 .env 文件，创建默认配置...")
        with open(env_file, 'w', encoding='utf-8') as f:
            f.write("# OpenAI API配置\n")
            f.write("OPENAI_API_KEY=your_openai_api_key_here\n")
            f.write("\n# 其他配置\n")
            f.write("FLASK_ENV=development\n")
            f.write("FLASK_DEBUG=True\n")
        print("✓ 已创建默认 .env 文件")
    return True

def main():
    """主函数"""
    print("=== Text2SQL评估系统简化后端启动 ===")
    print("📝 注意：这是简化版本，不包含Ragas评估功能")
    
    # 检查依赖
    if not check_requirements():
        print("正在安装基础依赖...")
        if not install_requirements():
            print("依赖安装失败，请手动安装")
            return
    
    # 检查环境变量
    if not check_env_file():
        print("请先配置环境变量文件")
        return
    
    # 启动Flask应用
    print("启动简化后端服务...")
    print("📊 访问地址: http://localhost:5000")
    print("🔍 健康检查: http://localhost:5000/api/health")
    print("📋 测试数据: http://localhost:5000/api/test-data")
    print("⏹️  按 Ctrl+C 停止服务")
    print("-" * 50)
    
    os.chdir("backend")
    try:
        subprocess.run([sys.executable, "app_simple.py"])
    except KeyboardInterrupt:
        print("\n服务已停止")
    except Exception as e:
        print(f"启动失败: {e}")

if __name__ == "__main__":
    main()
